package org.zbclan.bf2.rcon.home.server;

import java.util.Hashtable;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zbclan.bf2.rcon.common.server.ServerModel;
import org.zbclan.bf2.rcon.common.shared.GamePlayObject;
import org.zbclan.bf2.rcon.home.shared.GetGamePlayObjectCommand;
import org.zbclan.bf2.rcon.home.shared.GetGamePlayObjectResult;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class GetGamePlayObjectHandler implements
		ActionHandler<GetGamePlayObjectCommand, GetGamePlayObjectResult> {

	private static final Logger logger = LoggerFactory
			.getLogger(GetGamePlayObjectHandler.class);

	// private final Log logger;
	private final Provider<ServletContext> servletContext;
	private final Provider<HttpServletRequest> servletRequest;
	private ServerModel serverModel;

	@Inject
	public GetGamePlayObjectHandler(
			final Provider<ServletContext> servletContext,
			final Provider<HttpServletRequest> servletRequest,
			ServerModel serverModel) {
		// this.logger = logger;
		this.servletContext = servletContext;
		this.servletRequest = servletRequest;
		this.serverModel = serverModel;
	}

	public GetGamePlayObjectResult execute(final GetGamePlayObjectCommand cmd,
			final ExecutionContext context) throws ActionException {

		GamePlayObject gamePlayObject;
		String name = cmd.getName();
		String mode = cmd.getMode();

		try {

			Hashtable<String, GamePlayObject> level = serverModel.getLevels()
					.get(name);
			// GamePlayObject gamePlayObject = level.get(ServerZip.GPO_PREFIX
			// + mode + ServerZip.GPO_SUFFIX);
			gamePlayObject = level.get(mode);

		} catch (Exception cause) {
			logger.error("Unable to send message", cause);

			throw new ActionException(cause);
		}

		if (gamePlayObject == null) {
			throw new ActionException("invalid uri: " + name + "/" + mode);
		}

		GetGamePlayObjectResult result = new GetGamePlayObjectResult();
		result.setGamePlayObject(gamePlayObject);

		return result;
	}

	public void rollback(final GetGamePlayObjectCommand action,
			final GetGamePlayObjectResult result, final ExecutionContext context)
			throws ActionException {
		// Nothing to do here
	}

	public Class<GetGamePlayObjectCommand> getActionType() {
		return GetGamePlayObjectCommand.class;
	}
}